package com.thinkingstar.iads.test.beetl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.aop.interceptor.async.Async;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

@IocBean
@At("/beetl")
public class BeetlController {
	private static Log log = Logs.get(); 

	@At({"/", "/index"})
	@Ok("beetl:/test/index.html")
	public NutMap index() {
		NutMap obj = new NutMap();
		obj.setv("name","NB").setv("age",18);
		return obj;
	}

	@At("/table/?")
	@Ok("re:beetl:/test/table.html")
	public String dataTable(int number,HttpServletRequest req,HttpServletResponse res) {
		log.info("table请求.....................");
		if(req.getHeader("X-PJAX")==null){
			req.setAttribute("num",number);
			return "forward:/beetl/pjax";
		}
		int page = 10;
		String[] str = {"张三","李四","王五","赵六","钱七"};
		Random random = new Random(100);
		List<Map<String,Object>> list = new ArrayList<>();
		for(int i=0;i<page;i++){
			Map<String,Object> map = new HashMap<>();
			map.put("id", i);
			map.put("name",str[number-1]+i);
			map.put("phone",random.nextInt());
			list.add(map);
		}
		
		NutMap nMap = new NutMap();
		nMap.put("size", list.size()*str.length/page);
		nMap.put("list",list);
		nMap.put("num",number);
		req.setAttribute("obj", Json.toJson(nMap));
		return null;
	}

	@At("/pjax")
	@Ok("beetl:/test/pjax.html")
	public NutMap pjaxTable(HttpServletRequest req,HttpServletResponse res) {
		NutMap obj = new NutMap();
		obj.setv("name","pjax首页");
		return obj;
	}


	@At("/vue/?/?")
	@Ok("json:full")
	public NutMap getVue(String name,String age) {
		NutMap obj = new NutMap();
		obj.put("name", name);
		obj.put("age", age);
		return obj;
	}

	@At("/vue")
	@Ok("json:full")
	@AdaptBy(type = JsonAdaptor.class)
	public NutMap getVueJson(@Param("name")String name,@Param("age")String age) {
		NutMap obj = new NutMap();
		obj.put("name", name);
		obj.put("age", age);
		return obj;
	}



	@At("/async")
	@Ok("beetl:/test/index.html")
	public void async() {
		getInputData();//调用此异步方法
		log.info("任务结束");
	}

	//异步方法
	@Async
	public  void getInputData(){
		log.info("任务开始.....");
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		log.info("任务执行中....");
	}
}
